package com.qianbei.view.binding;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.qianbei.R;
import com.qianbei.bean.GetBindBean;
import com.qianbei.bean.GetBindBean2;
import com.qianbei.bean.GetBoxBody;
import com.qianbei.bean.GetBoxBody1;
import com.qianbei.bean.GetEmpty_Body;
import com.qianbei.bean.GetErroBean3;
import com.qianbei.bean.GetUpbox;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.MyApplication;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.okhttp.RequeastBean;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.util.DeviceUtil;
import com.qianbei.view.EpcDataBase;
import com.qianbei.view.db.Box;
import com.qianbei.view.db.BoxDb;
import com.qianbei.view.orm.DaoSession;
import com.qianbei.view.orm.RFID;
import com.qianbei.view.orm.RFIDDao;
import com.qianbei.view.orm.RequestPersistent;
import com.qianbei.view.transport.EmptyUPActivity;
import com.qianbei.view.util.JobBoxUtil;
import com.qianbei.view.util.MessageCallback;
import com.speedata.libuhf.IUHFService;
import com.speedata.libuhf.UHFManager;
import com.speedata.libuhf.bean.SpdInventoryData;
import com.speedata.libuhf.interfaces.OnSpdInventoryListener;

import org.greenrobot.greendao.query.QueryBuilder;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by gaoml on 2018/1/22.
 */

public class AddBingActivity extends BaseActivity {


    @Bind(R.id.bing_num)
    EditText bingNum;
    @Bind(R.id.bing_frd)
    TextView bingFrd;
    @Bind(R.id.taction_save)
    TextView tactionSave;
    @Bind(R.id.bing_box_type)
    TextView bingBoxType;

    private final static String[] boxTypeStr = {"医废小箱", "医废大箱", "医塑小箱", "医塑大箱"};
    private int init_progress = 0;
    private PowerManager pM = null;
    private PowerManager.WakeLock wK = null;
    private IUHFService iuhfService;
    /**
     * 上个Activity 传递过来的RFID
     */
    private String rfid;

    private String boxType;
    private String boxNum;

    private BoxDb boxDb;

    int type;
    /**
     * 是否上电状态
     */
    private AtomicBoolean isOpenDev = new AtomicBoolean(false);
    private RFIDDao rfidDao;
    /**
     * 成功上电
     */
    private AtomicBoolean isOpenSucces = new AtomicBoolean(false);
    private final String[] sex = {"医废小箱", "医废大箱", "医塑小箱", "医塑大箱"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gufei_bing_acitivty);
        ButterKnife.bind(this);
        setTitle("周转箱绑定");
        mTitle.setrightTitle("扫描");
        rfid = getIntent().getStringExtra("rfid");
        boxType = getIntent().getStringExtra("boxType");
        boxNum = getIntent().getStringExtra("boxNum");

        boxDb = new BoxDb(this);

        if (!TextUtils.isEmpty(rfid)) {
            bingFrd.setText(rfid);
            mTitle.setrightTitle("");
        }

        if (!TextUtils.isEmpty(boxNum)) {
            bingNum.setText(boxNum);
        }

        if (!TextUtils.isEmpty(boxType) && !boxType.equals("0")) {
            int boxTypeVal = Integer.valueOf(boxType);
            type = boxTypeVal;
            String boxTxt = sex[boxTypeVal - 1];
            bingBoxType.setText("周转箱类型 - " + boxTxt);
        }

        iuhfService = MyApplication.iuhfService;
        if (iuhfService != null) {

            iuhfService.setOnInventoryListener(new OnSpdInventoryListener() {
                @Override
                public void getInventoryData(SpdInventoryData var1) {

                    handler.sendMessage(handler.obtainMessage(111, var1));

                }
            });
        }
        newWakeLock();
        DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
        if (daoSession != null) {
            rfidDao = daoSession.getRFIDDao();
        }
    }

    boolean ishow = false;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 111:
                    SpdInventoryData var1 = (SpdInventoryData) msg.obj;
                    Log.d("gaoaa", var1.epc);
                    if (!TextUtils.isEmpty(var1.epc)) {
                        ring();
                        if (bingFrd != null) {
                            bingFrd.setText(var1.epc);
                            iuhfService.newInventoryStop();
                            mTitle.setrightTitle("扫描");
                            handler.removeCallbacksAndMessages(null);
                        }

                        ArrayList<String> rfid = new ArrayList<>();
                        rfid.add(var1.epc);
                        final EpcDataBase epcDataBase = new EpcDataBase(var1.epc, 1,
                                var1.rssi, var1.tid);
                        final Box box = boxDb.getBox(epcDataBase.epc, null);
                        Log.d("gaoaa", "box ok ");
                        if (box != null) {
                            epcDataBase.typeValue = String.valueOf(box.getBoxType());
                            epcDataBase.boxType = boxTypeStr[box.getBoxType() - 1];
                            epcDataBase.boxId = box.getBoxNum();
                            epcDataBase.epc = box.getRfid();
                            bingNum.setText(box.getBoxNum());
                            int boxTypeVal = Integer.valueOf(epcDataBase.typeValue);
                            type = boxTypeVal;
                            String boxTxt = sex[boxTypeVal - 1];
                            bingBoxType.setText("周转箱类型 - " + boxTxt);

                        }

                        RequeastBean bean = new RequeastBean("boxInfo",
                                "com.cygps.dubbo.WasteTransport.IPdaBoxManagement",
                                new GetBindBean2(rfid));
                        ServerControl sc = new ServerControl(bean);
                        sc.serverListener = new ServerControl.ServerListener() {

                            @Override
                            public void serverFinish(ServerResult sr) {
                                if (sr.isContinue) {
                                    JSONObject rfidRes = sr.bodyData.optJSONArray("data").optJSONObject(0);
                                    if (rfidRes.optInt("code") != -1) {
                                        if (rfidRes.optString("boxTypeVal") != null) {
                                            epcDataBase.boxType = rfidRes.optString("boxTypeVal");
                                        }
                                        if (rfidRes.optString("boxNo") != null) {
                                            epcDataBase.boxId = rfidRes.optString("boxNo");
                                        }
                                        if (rfidRes.optString("boxType") != null) {
                                            epcDataBase.typeValue = rfidRes.optString("boxType");
                                        }
                                        bingNum.setText(epcDataBase.boxId);
                                        int boxTypeVal = 0;
                                        try {
                                            boxTypeVal = Integer.valueOf(epcDataBase.typeValue);
                                        } catch (NumberFormatException e) {
                                            e.printStackTrace();
                                        }
                                        type = boxTypeVal;
                                        String boxTxt = "";
                                        if (boxTypeVal != 0) {
                                            boxTxt = sex[boxTypeVal - 1];
                                        }
                                        bingBoxType.setText("周转箱类型 - " + boxTxt);

                                        //如果本地库中没有当前周转箱 或信息不一致 更新本地库
                                        if (box == null || !box.getBoxNum().equals(epcDataBase.boxId) || !String.valueOf(box.getBoxType()).equals(epcDataBase.typeValue)) {
                                            JobBoxUtil.updateLocalBox(boxDb, epcDataBase);
                                        }

                                    } else {
                                        epcDataBase.boxType = null;
                                        epcDataBase.boxId = null;
                                        epcDataBase.typeValue = null;

                                    }

                                }
                            }
                        };
                        sc.OKpost();
                    }
                    break;
            }
        }
    };

    private void newWakeLock() {
        init_progress++;
        pM = (PowerManager) getSystemService(POWER_SERVICE);
        if (pM != null) {
            wK = pM.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
                    | PowerManager.ON_AFTER_RELEASE, "lock3992");
            if (wK != null) {
                wK.acquire();
                init_progress++;
            }
        }
        if (init_progress == 1) {
            Log.w("3992_6C", "wake lock init failed");
        }
    }


    /**
     * 上电开串口
     *
     * @return
     */
    private boolean openDev() {
        if (iuhfService.OpenDev() != 0) {
            new android.app.AlertDialog.Builder(this).setTitle(R.string.DIA_ALERT).setMessage(R.string.DEV_OPEN_ERR).setPositiveButton(R.string.DIA_CHECK, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    finish();
                }
            }).show();
            return true;
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            if (iuhfService != null && isOpenDev.get() == true) {
                iuhfService.newInventoryStop();
                iuhfService.CloseDev();
                //断电后选卡操作会失效，需要重新选卡（掩码）
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("StaticFieldLeak")
    @Override
    public void fClick(int id) {
        super.fClick(id);
        switch (id) {
            case R.id.tv_right:

                bingNum.setText("");
                bingBoxType.setText("周转箱类型");
                type = 0;
                mTitle.setrightTitle("正在扫描");
                //重复点扫描按钮时 只做一次上电操作
                if (isOpenDev.get() == false) {
                    isOpenDev.set(true);
                    new AsyncTask<Void, Void, Void>() {
                        @Override
                        protected Void doInBackground(Void... voids) {
                            try {
                                if (openDev()) {
                                    isOpenDev.set(false);
                                    return null;
                                } else {
                                    isOpenSucces.set(true);
                                }
                                iuhfService.set_antenna_power(MyApplication.setValue);
                            } catch (Exception e) {
                                e.printStackTrace();
                                isOpenDev.set(false);
                                return null;
                            }
                            iuhfService.newInventoryStart();
                            return null;
                        }
                    }.execute();

                } else if (isOpenSucces.get() == true) {
                    iuhfService.newInventoryStart();
                }
                break;
            default:
                break;
        }
    }


    public void show() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        //    设置一个单项选择下拉框
        /**
         * 第一个参数指定我们要显示的一组下拉单选框的数据集合
         * 第二个参数代表索引，指定默认哪一个单选框被勾选上，1表示默认'女' 会被勾选上
         * 第三个参数给每一个单选项绑定一个监听器
         */
        builder.setSingleChoiceItems(sex, 1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                type = which + 1;
                Toast.makeText(AddBingActivity.this, "选定为：" + sex[which], Toast.LENGTH_SHORT).show();
                bingBoxType.setText("周转箱类型 - " + sex[which]);
                dialog.dismiss();
            }
        });

        builder.show();
    }

    @OnClick({R.id.bing_select, R.id.taction_save, R.id.bing_frd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bing_select:
                show();
                break;
            case R.id.taction_save:
                if (type == 0) {
                    new MsgAlert().show("请选择周转箱类型");
                } else if (TextUtils.isEmpty(bingNum.getText().toString())) {
                    new MsgAlert().show("请输入周转箱号码");
                } else if (TextUtils.isEmpty(boxNum) && TextUtils.isEmpty(bingFrd.getText().toString())) {
                    new MsgAlert().show("请扫描录入RFID");
                } else {
                    showD();
                }

                break;

            case R.id.bing_frd:
                //点输入框时触发扫描
                findViewById(R.id.tv_right).callOnClick();
                break;
        }
    }

    /**
     * 提示用户 绑定
     */
    public void showD() {
        AlertDialog dialog = new AlertDialog.Builder(this)
//                .setTitle("是否绑定此车")//设置对话框的标题
                .setMessage("是否确认绑定？")//设置对话框的内容
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        interrupt(bingNum.getText().toString(), bingFrd.getText().toString()
                                , type + "");
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }

    private void ring() {


        Uri notification = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.beep_once);
        if (notification == null) return;
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

        Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(500);
    }

    /**
     *
     */
    private void interrupt(String boxNo, final String rfid, String boxType) {


        RequeastBean bean = new RequeastBean("save", "com.cygps.dubbo.WasteTransport.IPdaBoxManagement",
                new GetBindBean(boxNo, rfid, boxType));

        final Intent mIntent = new Intent();
        mIntent.putExtra("boxNum", boxNo);
        mIntent.putExtra("rfid", rfid);
        mIntent.putExtra("boxType", boxType);

        Box box = new Box(rfid, boxNo, Integer.valueOf(boxType));
        boxDb.update(box);

        if (!DeviceUtil.isNetworkAvailable()) {//没用网络 缓存数据到内存
//            MyApplication.netList.add(bean);bug001
            DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
            RequestPersistent requestPersistent = new RequestPersistent();
            requestPersistent.setServiceName(bean.serviceName);
            requestPersistent.setServiceMethod(bean.serviceMethod);
            requestPersistent.setServiceBody(new Gson().toJson(bean.serviceBody));
            requestPersistent.setMethodClass(GetBindBean.class.getName());
            daoSession.getRequestPersistentDao().insertOrReplace(requestPersistent);
            iuhfService.newInventoryStop();
            //new MsgAlert().show("现在没用网络，数据已保存 有网络的时候会自动提交");
            handler.removeCallbacksAndMessages(null);
            iuhfService.newInventoryStop();
            if (!TextUtils.isEmpty(rfid) || !TextUtils.isEmpty(boxNum)) {
                new MsgAlert().show("绑定成功");
                // 设置结果，并进行传送
                AddBingActivity.this.setResult(0, mIntent);
                finish();
            }
        } else {
            ServerControl sc = new ServerControl(bean);
            sc.serverListener = new ServerControl.ServerListener() {

                @Override
                public void serverFinish(ServerResult sr) {

                    if (sr.isContinue) {
                        new MsgAlert().show("绑定成功");
                        handler.removeCallbacksAndMessages(null);
                        iuhfService.newInventoryStop();
                        //finish();

                        bingNum.setText("");
                        bingFrd.setText("");

                        if (!TextUtils.isEmpty(rfid) || !TextUtils.isEmpty(boxNum)) {
                            // 设置结果，并进行传送
                            AddBingActivity.this.setResult(0, mIntent);
                            finish();
                        }
                    } else {
                        if (!TextUtils.isEmpty(rfid) || !TextUtils.isEmpty(boxNum)) {
                            // 设置结果，并进行传送
                            AddBingActivity.this.setResult(0, mIntent);
                            finish();
                        }
                    }

                }
            };
            new ProgressDialog(mContext).OKpost(sc);

        }

    }

}
